from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.config.database import get_db
from app.models.user import User as UserModel
from app.schemas.user import User as UserSchema
from app.schemas.response import APIResponse
from app.utils.jwt import verify_password, create_access_token, get_password_hash
from app.utils.dependencies import get_current_active_user
from app.utils.responses import success_response, error_response
from app.config.settings import settings
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="/auth", tags=["认证"])

class LoginRequest(BaseModel):
    """登录请求模型"""
    username: str
    password: str

class LoginResponse(BaseModel):
    """登录响应模型"""
    access_token: str
    token_type: str
    user: UserSchema

class UserInfoResponse(BaseModel):
    """用户信息响应模型"""
    user: UserSchema

class ChangePasswordRequest(BaseModel):
    """修改密码请求模型"""
    old_password: str
    new_password: str

@router.post("/login", response_model=APIResponse[LoginResponse])
def login(
    login_request: LoginRequest,
    db: Session = Depends(get_db)
):
    """用户登录"""
    # 验证用户
    user = db.query(UserModel).filter(UserModel.username == login_request.username).first()
    if not user or not verify_password(login_request.password, str(user.password)):
        return error_response(
            message="用户名或密码错误",
            code=status.HTTP_401_UNAUTHORIZED
        )
    
    # 检查用户状态
    if getattr(user, 'status') != 1:  # 1表示启用状态
        return error_response(
            message="用户已被禁用",
            code=status.HTTP_403_FORBIDDEN
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
    access_token = create_access_token(
        data={"sub": str(user.id)}, 
        expires_delta=access_token_expires
    )
    
    # 返回用户信息和令牌
    user_schema = UserSchema.from_orm(user)
    response_data = LoginResponse(
        access_token=access_token,
        token_type="bearer",
        user=user_schema
    )
    
    return success_response(data=response_data, message="登录成功")

@router.post("/logout", response_model=APIResponse[None])
def logout():
    """用户登出"""
    # JWT是无状态的，服务端不需要特殊处理
    # 前端应删除存储的令牌
    return success_response(message="登出成功")

@router.get("/userinfo", response_model=APIResponse[UserInfoResponse])
def get_user_info(
    current_user: UserModel = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    user_schema = UserSchema.from_orm(current_user)
    response_data = UserInfoResponse(user=user_schema)
    return success_response(data=response_data, message="获取用户信息成功")

@router.post("/change-password", response_model=APIResponse[None])
def change_password(
    change_password_request: ChangePasswordRequest,
    current_user: UserModel = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """修改当前用户密码"""
    # 验证旧密码是否正确
    if not verify_password(change_password_request.old_password, str(current_user.password)):
        return error_response(
            message="原密码错误",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 检查新密码是否与旧密码相同
    if verify_password(change_password_request.new_password, str(current_user.password)):
        return error_response(
            message="新密码不能与原密码相同",
            code=status.HTTP_400_BAD_REQUEST
        )
    
    # 更新密码
    current_user.password = get_password_hash(change_password_request.new_password)
    db.commit()
    
    return success_response(message="密码修改成功")